package fileupload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * 升级版
 **/
public class Server2 {
    public static void main(String[] args) throws IOException {
        // 步骤1：将ServerSocket放到循环外部，创建一次就行，用完不需要关闭
        ServerSocket ss = new ServerSocket(8888);

        // 步骤2：这里添加一个死循环，让服务端一直保持工作状态
        while (true) {

            // 步骤3：改了这个地方，将原先写死的文件名，改成使用UUID去生成
            FileOutputStream fos = new FileOutputStream(UUID.randomUUID().toString() + ".png");
            Socket accept = ss.accept();
            InputStream is = accept.getInputStream();
            int b;
            while ((b = is.read()) != -1) {
                fos.write(b);
            }

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
            bw.write("文件上传成功");
            bw.newLine();
            bw.flush();

            fos.close();
            bw.close();
            is.close();
            accept.close();
        }

        // ss.close();
    }
}
